package com.stenio.fancat.controller.baby;

import com.baomidou.mybatisplus.plugins.Page;
import com.stenio.fancat.controller.Result;
import com.stenio.fancat.domain.baby.FcBehavior;
import com.stenio.fancat.form.baby.BehaviorForm;
import com.stenio.fancat.service.baby.BehaviorService;
import com.stenio.fancat.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author liuan
 * @create 2019-01-16 18:07
 */

@RestController
@RequestMapping("task")
public class BehaviorController {

    @Autowired
    private BehaviorService behaviorService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("add")
    @ResponseBody
    public Result<FcBehavior> add(@RequestBody BehaviorForm behaviorForm){
        Result<FcBehavior> result = new Result();
        FcBehavior behavior = behaviorService.saveTask(behaviorForm);
        result.setData(behavior);
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        return result;
    }

    @PostMapping("page")
    @ResponseBody
    public Result page(@RequestBody BehaviorForm behaviorForm){
        Result<Map<String,Object>> result = new Result();
        Page<FcBehavior> page = behaviorService.selectByPage(behaviorForm);
        Map<String,Object> data = new HashMap<>();
        if(page!=null){
            data.put("current",page.getCurrent());
            data.put("pages",page.getPages());
            data.put("size",page.getSize());
            data.put("total",page.getTotal());
            data.put("records",page.getRecords());
        }
        result.setData(data);
        return result;
    }

    @PostMapping("onOff/{id}/{status}")
    @ResponseBody
    public Result onOff(@PathVariable String id, @PathVariable Integer status){
        Result<FcBehavior> result = new Result();
        try {
            result.setData(behaviorService.onOff(id,status));
        } catch (Exception e) {
            result.setFlag(Result.FLAG.failure);
            result.setMsg("上下架状态不合法");
        }
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        return result;
    }

    @GetMapping("get/{id}")
    @ResponseBody
    public Result get(@PathVariable String id){
        Result<FcBehavior> result = new Result();
        result.setData(behaviorService.getById(id));
        return result;
    }

    @PostMapping("update")
    @ResponseBody
    public Result update(@RequestBody BehaviorForm behaviorForm){
        Result<FcBehavior> result = new Result();
        result.setData(behaviorService.updateVender(behaviorForm));
        Set<String> keys = redisTemplate.keys("*");
        redisTemplate.delete(keys);
        return result;
    }

}
